<?php

namespace app\services\analysis;

use app\dao\activity\score\StoreScoreDao;
use app\services\BaseServices;
use app\model\user\User;
use app\model\user\UserBill;

class ScoreServices extends BaseServices
{
    public function __construct(StoreScoreDao $dao)
    {
        $this->dao = $dao;
    }

    /**
     * @return int[]
     */
    public function overview(){
        $data = [
            'usable' => 0,//可用的
            'outcom' => 0,//累计消耗
            'income' => 0,//累计发放
            'outcom_proportion' => 0.00,//消耗率
            'overdue' => 0//过期积分
        ];
        $usable = User::field('sum(integral) usable')->where('status',1)->where('is_del',0)->find()->toArray();
        $data['usable'] = $usable['usable'] ? (int)$usable['usable'] : 0;

        $outcom = UserBill::field('sum(number) outcom')->where('pm',0)->where('category','integral')->find()->toArray();
        $data['outcom'] = $outcom['outcom'] ? (int)$outcom['outcom'] : 0;

        $income = UserBill::field('sum(number) income')->where('pm',1)->where('category','integral')->find()->toArray();
        $data['income'] = $income['income'] ? (int)$income['income'] : 0;

        $data['outcom_proportion'] = $this->truncateDecimal($data['outcom']/$data['income'] * 100);
        return $data;
    }

    /**
     * @return array
     */
    public function usable_detail(){
        $data = [
            ['title' => '1-1000', 'start' => 1, 'end' => 1000, 'number' => 20, 'proportion' => 20.00],
            ['title' => '1001-1万', 'start' => 1001, 'end' => 10000, 'number' => 40, 'proportion' => 40.00],
            ['title' => '1万-10万', 'start' => 10001, 'end' => 1000000, 'number' => 30, 'proportion' => 30.00],
            ['title' => '10万-50万', 'start' => 1000001, 'end' => 5000000, 'number' => 10, 'proportion' => 10.00],
            ['title' => '50万-100万', 'start' => 5000001, 'end' => 10000000, 'number' => 0, 'proportion' => 0.00],
            ['title' => '100万以上', 'start' => 10000001, 'end' => 999999999, 'number' => 0, 'proportion' => 0.00],
        ];

        $total = 0;
        foreach ($data as $key => $val){
            $users = User::field('ifnull(count(*),0) number')->where('integral','>=',$val['start'])->where('integral','<=',$val['end'])
                ->where('status',1)->where('is_del',0)->find()->toArray();

            $data[$key]['number'] = $users['number'] ? (int)$users['number'] : 0;
            $total += $data[$key]['number'];
        }
        if($total > 0){
            foreach ($data as $key => $val){
                $data[$key]['proportion'] = $this->truncateDecimal($val['number']/$total * 100);
            }
        }
        return $data;
    }

    /**
     * @return array|array[]
     */
    public function income_detail(){
        $data = [
            ['title' => '管理员发放','type' => 'admin', 'number' => 0, 'proportion' => 0.00],
            ['title' => '购买商品','type' => 'order_give_integral', 'number' => 0, 'proportion' => 0.00],
            ['title' => '签到','type' => 'sign', 'number' => 0, 'proportion' => 0.00],
            ['title' => '积分任务','type' => 'task', 'number' => 0, 'proportion' => 0.00],
        ];

        $total = 0;
        $bills = UserBill::field('sum(number) number, type')->where('pm',1)->where('category','integral')->group('type')->select()->toArray();
        if($bills){
            foreach ($bills as $bill){
                foreach ($data as $key => $val){
                    if($bill['type'] == $val['type']){
                        $data[$key]['number'] = $bill['number'];
                    }
                }
                $total += $bill['number'];
            }
        }
        if($total > 0){
            foreach ($data as $key => $val){
                $data[$key]['proportion'] = $this->truncateDecimal($val['number']/$total * 100);
            }
        }
        return $data;
    }

    /**
     * @return array|array[]
     */
    public function outcom_detail(){
        $data = [
            ['title' => '积分兑换商品','type' => 'storeIntegral_use', 'number' => 0, 'proportion' => 0.00],
            ['title' => '积分兑换优惠券','type' => 'storeCoupon_use', 'number' => 0, 'proportion' => 0.00],
        ];
        $total = 0;
        $bills = UserBill::field('sum(number) number, type')->where('type','in', ['storeIntegral_use','storeCoupon_use'])->where('pm',0)->where('category','integral')->group('type')->select()->toArray();
        if($bills){
            foreach ($bills as $bill){
                foreach ($data as $key => $val){
                    if($bill['type'] == $val['type']){
                        $data[$key]['number'] = $bill['number'];
                    }
                }
                $total += $bill['number'];
            }
        }
        if($total > 0){
            foreach ($data as $key => $val){
                $data[$key]['proportion'] = $this->truncateDecimal($val['number']/$total * 100);
            }
        }
        return $data;
    }

    /**
     * @return array
     */
    public function year_detail(){
        $year = date('Y');
        $months = $this->getAllMonthsOfYear($year);

        $outcom = [];
        $outcomList = UserBill::field("DATE_FORMAT(FROM_UNIXTIME(add_time), '%Y-%m') mon,sum(number) number")->where('pm',0)->where('category','integral')->where('type','in', ['storeIntegral_use','storeCoupon_use'])->group("DATE_FORMAT(FROM_UNIXTIME(add_time), '%Y-%m')")->select()->toArray();
        foreach($months as $mon){
            $number = 0;
            foreach($outcomList as $val){
                if($val['mon'] == $mon){
                    $number = intval($val['number']);
                }
            }
            $outcom[] = $number;
        }

        $income = [];
        $outcomList = UserBill::field("DATE_FORMAT(FROM_UNIXTIME(add_time), '%Y-%m') mon,sum(number) number")->where('pm',1)->where('category','integral')->group("DATE_FORMAT(FROM_UNIXTIME(add_time), '%Y-%m')")->select()->toArray();
        foreach($months as $mon){
            $number = 0;
            foreach($outcomList as $val){
                if($val['mon'] == $mon){
                    $number = intval($val['number']);
                }
            }
            $income[] = $number;
        }

        $data = [
            'date' => $months,
            'outcom' => $outcom,
            'income' => $income
        ];
        return $data;
    }

    /**
     * @param $numberString
     * @param int $precision
     * @return string
     */
    public function truncateDecimal($numberString, $precision = 2) {
        // 查找小数点的位置
        $pos = strpos($numberString, '.');
        if ($pos === false) {
            // 如果没有小数点，则直接返回字符串（或添加小数点并填充零）
            return $numberString . '.' . str_repeat('0', $precision);
        }
        // 截取小数点后的部分
        $decimalPart = substr($numberString, $pos + 1);
        // 保留指定的小数位数
        $truncatedDecimalPart = substr($decimalPart, 0, $precision);
        // 拼接整数部分和截取后的小数部分
        return substr($numberString, 0, $pos + 1) . $truncatedDecimalPart;
    }

    /**
     * @param $year
     * @return array
     */
    public function getAllMonthsOfYear($year) {
        $months = array();
        for ($i = 1; $i <= 12; $i++) {
            $months[] = date('Y-m', strtotime("$year-$i-01")); // 使用date和strtotime函数获取月份的全名
        }
        return $months;
    }
}